//
//  UserCount.swift
//  weibo-mxm
//
//  Created by 马晓敏 on 16/1/13.
//  Copyright © 2016年 马晓敏. All rights reserved.
//

import UIKit
/*
使用归档与解归档做数据的保存和获取




*/

class UserCount: NSObject ,NSCoding{
    var access_token:String?
    var expires_in:NSTimeInterval = 0{
        didSet{
      
        expires_date = NSDate(timeIntervalSinceNow: expires_in)
     
        }
    
    }
    //过期日期 开发者过期日期是5年,普通用户过期日期是3天
    var expires_date:NSDate?
    var uid:String?
    
    var name:String?
    var avatar_large:String?
   //kvc设置初始值
    init(dict:[String:AnyObject]) {
        super.init()
       setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {   }

  //重写对象的描述信息
  override   var  description:String{
    let  keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
    
    let dict = self.dictionaryWithValuesForKeys(keys)
    
    return dict.description
    
    

    
    
    
    
    
    }
   //保存自定义对象
func saveAccount(){
 //保存到沙河中
let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
   //将对象保存到沙河路径中
    NSKeyedArchiver.archiveRootObject(self, toFile: path)
    print(path)
    
    }
    
 //获取磁盘中的归档对象 (类方法)
    class func loadUserAccount() ->UserCount? {
        
      let path  = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
      if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as?UserCount{
       //并且token没有过期,最后才会返回一个用户账户对象
        
        if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
          return account
        
        }
                }
        
       return nil
    }
    
    
    
  //实现协议方法
    //解归档  将二进制数据 - >自定义对象 和反序列化类似
    required init?(coder aDecoder: NSCoder) {
    
access_token = aDecoder.decodeObjectForKey("access_token") as?String
    
    expires_in = aDecoder.decodeDoubleForKey("expires_in")
    
    uid = aDecoder.decodeObjectForKey("uid") as?String
    
    name = aDecoder.decodeObjectForKey("name") as?String
    
    avatar_large = aDecoder.decodeObjectForKey("avatar_large") as?String
        
     expires_date = aDecoder.decodeObjectForKey("expires_date") as?NSDate
        
    }
    //归档 将自定义对象 ->转为二进制->保存到磁盘中
    func encodeWithCoder(aCoder: NSCoder) {
        
    aCoder.encodeObject(access_token,forKey:"access_token")
        
    aCoder.encodeDouble(expires_in, forKey: "expires_in")
        
    aCoder.encodeObject(uid, forKey: "uid")
        
    aCoder.encodeObject(name, forKey: "name")
        
    aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    aCoder.encodeObject(expires_date, forKey: "expires_date")
        
    }
    
}
